# app/routes/file.py
from flask import Blueprint, jsonify, request
from app.utils.security import token_required
from app.services.file_service import FileService
from app.models import File
from app.utils.response_utils import (
    success_response,
    error_response,
    ResponseCode
)

# 创建蓝图对象
files_bp = Blueprint('files', __name__)


@files_bp.route('/init_upload', methods=['POST'])
@token_required
def init_upload(currentUserId):
    data = request.json
    filename = data.get('file_name')
    size = data.get('size')
    mime_type = data.get('mime_type')
    total_chunks = data.get('total_chunks')

    if not all([filename, size, mime_type, total_chunks]):
        return error_response(ResponseCode.BAD_REQUEST, 'Missing required parameters')

    # 创建上传任务
    task_id = FileService.create_upload_task(
        uploader_id=currentUserId,
        filename=filename,
        size=size,
        mime_type=mime_type,
        total_chunks=total_chunks
    )

    return success_response(
        data={'task_id': task_id},
        message='Upload initialized'
    )


@files_bp.route('/upload_chunk', methods=['POST'])
@token_required
def upload_chunk(currentUserId):
    # 获取分片数据
    task_id = request.form.get('task_id')
    chunk_index = int(request.form.get('chunk_index'))
    chunk = request.files.get('chunk')

    # 验证参数
    if not task_id or chunk_index is None or not chunk:
        return error_response(ResponseCode.BAD_REQUEST, 'Invalid parameters')

    # 保存分片
    result = FileService.save_chunk(
        task_id=task_id,
        chunk_index=chunk_index,
        chunk_data=chunk,
        uploader_id=currentUserId
    )

    return success_response(
        data={
            'uploaded_chunks': result['uploaded_chunks'],
            'status': result['status']
        },
        message='Chunk uploaded'
    )


@files_bp.route('/complete_upload', methods=['POST'])
@token_required
def complete_upload(currentUserId):
    data = request.json
    task_id = data.get('task_id')
    channel_id = data.get('channel_id','')
    direct_chat_id = data.get('direct_chat_id','')

    if not task_id:
        return error_response(ResponseCode.BAD_REQUEST, 'Task ID required')

    # 完成上传
    file = FileService.complete_upload(task_id=task_id, uploader_id=currentUserId,channel_id=channel_id,direct_chat_id=direct_chat_id)

    return success_response(
        data={
            'file_id': file.file_id,
            'file_url': file.file_url,  # 假设有生成URL的方法
            'file_name': file.original_name,
            'mime_type': file.mime_type,
            'size': file.size
        },
        message='File upload completed'
    )


@files_bp.route('/deleteFile', methods=['POST'])
@token_required
def delete_file(currentUserId):
    data = request.get_json()
    file_id = data.get('file_id')
    try:
        # 删除文件
        FileService.delete_file(file_id,currentUserId)

        return success_response(
            message='文件删除成功'
        )
    except Exception as e:
        print(str(e))
        return error_response(ResponseCode.UNKNOWN_ERROR, message='未知错误')


# 获取当前用户的所有文件
@files_bp.route('/user_files', methods=['GET'])
@token_required
def get_user_files(currentUserId):
    try:
        files = FileService.get_user_files(currentUserId)
        return success_response(
            data={'files': files},
            message='文件列表获取成功'
        )
    except Exception as e:
        return error_response(ResponseCode.INTERNAL_SERVER_ERROR, str(e))

# 按类型获取文件
@files_bp.route('/by_type', methods=['GET'])
@token_required
def get_files_by_type(currentUserId):
    try:
        mime_type = request.args.get('type')  # 例如 'image/%', 'video/%', 'application/pdf'
        if not mime_type:
            return error_response(ResponseCode.BAD_REQUEST, 'Missing file type parameter')

        files = FileService.get_files_by_type(currentUserId, mime_type)
        return success_response(
            data={'files': files},
            message=f'成功获取{mime_type}类型文件'
        )
    except Exception as e:
        return error_response(ResponseCode.INTERNAL_SERVER_ERROR, str(e))


# 新增：文件访问路由 (放在文件末尾)
@files_bp.route('/uploads/<filename>')
def serve_file(filename):
    """提供上传文件的访问服务"""
    from flask import send_from_directory
    from flask import current_app

    # 安全验证：确保请求的文件名格式有效
    if not filename or '.' not in filename:
        return error_response(ResponseCode.NOT_FOUND, "Invalid filename")

    # 验证文件扩展名是否允许 (可选安全措施)
    allowed_extensions = {'png', 'jpg', 'jpeg', 'gif', 'mp4', 'pdf', 'txt', 'doc', 'docx','zip','xmind','wav'}
    print(filename.split('.')[-1].lower())
    if filename.split('.')[-1].lower() not in allowed_extensions:
        return error_response(ResponseCode.OPERATION_NOT_ALLOWED, "文件类型错误")

    # 发送文件
    return send_from_directory(current_app.config['UPLOAD_FOLDER'], filename)

@files_bp.route('/getUserFileList', methods=["POST"])
@token_required
def get_user_fileList(currentUserId):
    data = request.get_json()
    pageCur = data.get('pageCur')
    pageSize = data.get('pageSize')

    result = FileService.get_user_files(user_id=currentUserId,pageCur=pageCur,pageSize=pageSize)

    if isinstance(result, tuple):  # 如果是错误响应
        return error_response(
            code=ResponseCode.PERMISSION_DENIED,
            message=result[0],
            http_code=result[1]
        )

    return success_response(
        data=result,
        message=f'success'
    )